<template>
  <div class="dashbord">
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item class="ml20">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="~"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          @change="chooseDate"
          >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-select v-model="platform" @change="choosePlat">
          <el-option
            v-for="item in platformList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-row :xl="24" :lg="24" :xs="24" :gutter="10" class="mt10">
      <el-col :lg="6" :sm="6" :xs="12"
              v-for="(item, index) in dataList"
              :key="index"
              :index="index"
              :item="item"
              style="padding:5px;"
        >
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>{{item.title}}</span>
          </div>
          <div class="content">
            <p class="info"><span>{{endDateStr}}</span></p>
            <p class="data"><span class="num">{{item.data}}</span><span>{{item.unit}}</span></p>
            <p class="info">环比
              <span class="rate"  :class="[item.dayRate.indexOf('-') != -1 ? 'bottom' : 'top']">
                <i :class="[item.dayRate.indexOf('-') != -1 ? 'el-icon-caret-bottom' : 'el-icon-caret-top']"></i>{{item.dayRate}}
              </span>，同比
              <span class="rate"  :class="[item.weekRate.indexOf('-') != -1 ? 'bottom' : 'top']">
                <i  :class="[item.weekRate.indexOf('-') != -1 ? 'el-icon-caret-bottom' : 'el-icon-caret-top']"></i>{{item.weekRate}}
              </span>
            </p>
          </div>
        </el-card>
      </el-col>
      <!--在线人数-->
      <el-col :lg="12" :sm="12" :xs="24"
              style="padding:5px;"
        >
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>在线人数
              <span class="info" style="display: inline-block;float: right;">{{startDate}}~{{endDate}}</span>
            </span>
          </div>
          <div class="content" style="overflow:hidden;">
            <div style="float:left;width:50%;">
              <p class="info"><span>{{endDateStr}}</span></p>
              <div style="float:left;" class="data" ><span class="num">{{onlineData.data}}</span><span>人</span></div>
              <div class="flRate">
                <p class="info">
                  环比
                  <span class="rate"  :class="[onlineData.dayRate.indexOf('-') != -1 ? 'bottom' : 'top']">
                     <i  :class="[onlineData.dayRate.indexOf('-') != -1 ? 'el-icon-caret-bottom' : 'el-icon-caret-top']"></i>
                    {{onlineData.dayRate}}
                  </span>
                </p>
                <p class="info">
                  同比
                  <span class="rate"  :class="[onlineData.weekRate.indexOf('-') != -1 ? 'bottom' : 'top']">
                     <i  :class="[onlineData.weekRate.indexOf('-') != -1 ? 'el-icon-caret-bottom' : 'el-icon-caret-top']"></i>
                    {{onlineData.weekRate}}
                  </span>
                </p>
              </div>
            </div>
            <div class="flNum">
              <p class="info">
                合计
                  <span class="number">
                    {{onlineData.tot}}
                  </span>
                人
              </p>
              <p class="info">
                均值
                  <span class="number" >
                    {{onlineData.aver}}
                  </span>
                人
              </p>
            </div>
          </div>
          <chartLine :data="onlineChart" :xData="xAxisData"  :yData="onlineData.dataArr"></chartLine>
          <!--<div id="onlineChart" class="chart" :style="{width: '100%', height: '200px'}"></div>-->
        </el-card>
      </el-col>
      <!--付费金额-->
      <el-col :lg="12" :sm="12" :xs="24"
              style="padding:5px;"
        >
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>付费金额
              <span class="info" style="display: inline-block;float: right;">{{startDate}}~{{endDate}}</span>
            </span>
          </div>
          <div class="content" style="overflow:hidden;">
            <div style="float:left;width:50%;">
              <p class="info"><span>{{endDateStr}}</span></p>
              <div style="float:left;" class="data" ><span class="num">{{paymentData.data}}</span><span>万</span></div>
              <div class="flRate">
                <p class="info">
                  环比
                  <span class="rate"  :class="[paymentData.dayRate.indexOf('-') != -1 ? 'bottom' : 'top']">
                     <i  :class="[paymentData.dayRate.indexOf('-') != -1 ? 'el-icon-caret-bottom' : 'el-icon-caret-top']"></i>
                    {{paymentData.dayRate}}
                  </span>
                </p>
                <p class="info">
                  同比
                  <span class="rate"  :class="[paymentData.weekRate.indexOf('-') != -1 ? 'bottom' : 'top']">
                     <i  :class="[paymentData.weekRate.indexOf('-') != -1 ? 'el-icon-caret-bottom' : 'el-icon-caret-top']"></i>
                    {{paymentData.weekRate}}
                  </span>
                </p>
              </div>
            </div>
            <div class="flNum">
              <p class="info">
                合计
                  <span class="number">
                    {{paymentData.tot}}
                  </span>
                万
              </p>
              <p class="info">
                均值
                  <span class="number" >
                    {{paymentData.aver}}
                  </span>
                万
              </p>
            </div>
          </div>
          <chartLine :data="paymentChart" :xData="xAxisData"  :yData="paymentData.dataArr"></chartLine>
        </el-card>
      </el-col>
      <!--游戏数据-->
      <el-col :lg="24" :sm="24" :xs="24"
              style="padding:5px;"
        >
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>游戏数据
              <span class="info" style="display: inline-block;float: right;">{{endDateStr}}</span>
            </span>
          </div>
          <el-table :data="tableData" height="420" v-loading="tableLoading">
            <el-table-column label="序号" width="60" type="index" fixed>
            </el-table-column>
            <el-table-column prop="game_name" label="游戏" width="120" fixed>
              <template slot-scope="scope">
                <!-- :href="scope.row.game_name" -->
                <a target="_blank" style="color: #409eff">
                  {{ scope.row.game_name }}
                </a>
              </template>
            </el-table-column>
            <el-table-column sortable prop="pay" label="流水" width="90">
            </el-table-column>
            <el-table-column sortable prop="grade" label="评分" width="90">
            </el-table-column>
            <el-table-column sortable prop="cos" label="投入" width="90">
            </el-table-column>
            <el-table-column sortable prop="divide" label="分成" width="90">
            </el-table-column>
            <el-table-column sortable prop="reg" label="注册数" width="90">
            </el-table-column>
            <el-table-column sortable prop="role_rate" label="转化率" width="90">
              <template slot-scope="scope">
                <div>
                  {{
                  scope.row.role_rate
                  ? (scope.row.role_rate / 100).toFixed(1) + "%"
                  : 0
                  }}
                </div>
              </template>
            </el-table-column>
            <el-table-column sortable prop="actives" label="活跃数" width="90">
            </el-table-column>

            <!--  <el-table-column sortable prop="npays" label="新付款" width="90">
            </el-table-column> -->
            <el-table-column sortable prop="pay_new" label="新付款金额" width="120">
            </el-table-column>
            <el-table-column sortable prop="npayRate" label="新付率" width="90">
              <template slot-scope="scope">
                <div>
                  {{ scope.row.npayRate ? scope.row.npayRate + "%" : 0 }}
                </div>
              </template>
            </el-table-column>

            <!-- <el-table-column sortable prop="odpays" label="旧付款" width="90">
            </el-table-column> -->
            <el-table-column sortable prop="pay_old" label="旧付款金额" width="120">
            </el-table-column>
            <el-table-column sortable prop="odpayRate" label="旧付率" width="90">
              <template slot-scope="scope">
                <div>
                  {{ scope.row.odpayRate ? scope.row.odpayRate + "%" : 0 }}
                </div>
              </template>
            </el-table-column>

            <el-table-column sortable prop="pays" label="付费人数" width="100">
            </el-table-column>
            <el-table-column sortable prop="payRate" label="付费率" width="90">
              <template slot-scope="scope">
                <div>
                  {{ scope.row.payRate ? scope.row.payRate + "%" : 0 }}
                </div>
              </template>
            </el-table-column>

            <el-table-column sortable prop="arpu" label="ARPU" width="90">
            </el-table-column>
            <el-table-column sortable prop="arppu" label="ARPPU" width="100">
            </el-table-column>
            <el-table-column sortable prop="remain2" label="次留" width="90">
            </el-table-column>
            <el-table-column sortable prop="remain3" label="3留" width="90">
            </el-table-column>
            <el-table-column sortable prop="remain7" label="7留" width="90">
            </el-table-column>
            <el-table-column sortable prop="remain15" label="15留" width="90">
            </el-table-column>
            <el-table-column sortable prop="ltv" label="LTV1" width="90">
            </el-table-column>
            <el-table-column sortable prop="ltv7" label="LTV7" width="90">
            </el-table-column>
            <el-table-column sortable prop="ltv15" label="LTV15" width="90">
            </el-table-column>
            <el-table-column sortable prop="ltv30" label="LTV30" width="90">
            </el-table-column>
            <el-table-column sortable prop="ltv60" label="LTV60" width="90">
            </el-table-column>
            <el-table-column sortable prop="ltv120" label="LTV120" width="100">
            </el-table-column>
            <el-table-column sortable prop="avg_level" label="平均等级" width="100">
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

    </el-row>



  </div>
</template>
<script>
  import chartLine from "@/components/Echarts/line";
  export default {
  name: "dashbord",
  components: {
    chartLine,
  },
  data() {
    return {
      name: "dashbord",
      role: localStorage.getItem("role"),
      user_name: localStorage.getItem("user_name"),
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
          picker.$emit('pick', [start, end]);
        }
        }, {
          text: '最近一个月',
            onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
            onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      dateRange: '',
      platformList: [
      {
        value: 'all',
        label: '全部'
      },
      {
        value: 'web',
        label: '页游'
      },
      {
        value: 'h5',
        label: '手游'
      }
     ],
      platform:'all',
      startDate:"",
      endDate:"",
      endDateStr:"",
      dataList:[
        {
          title: '活跃用户数',
          data: 6800,
          unit: "人",
          dayRate: '11.62%',
          weekRate: '17.62%'
        },
        {
          title: '新增用户数',
          data: 2013,
          unit: "人",
          dayRate: '15.69%',
          weekRate: '22.89%'
        },
        {
          title: '付费用户数',
          data: 2389,
          unit: "人",
          dayRate: '8.69%',
          weekRate: '20.89%'
        },
        {
          title: 'ARPU',
          data: 577,
          unit: "",
          dayRate: '-41.06%',
          weekRate: '-34.51%'
        },
        {
          title: '流水',
          data: 392.21,
          unit: "万",
          dayRate: '-8.69%',
          weekRate: '-20.89%'
        },
        {
          title: '付费收入',
          data: 392.21,
          unit: "万",
          dayRate: '-34.69%',
          weekRate: '-22.89%'
        },
        {
          title: '市场投入',
          data: 2389,
          unit: "万",
          dayRate: '-8.69%',
          weekRate: '-20.89%'
        },
        {
          title: 'ARPPU',
          data: 3207,
          unit: "",
          dayRate: '-38.69%',
          weekRate: '-36.46%'
        },
      ],
//      xAxisData: ['11-25', '11-26', '11-27', '11-28', '11-29', '11-30', '12-01'], // x轴数据，可根据需求
      xAxisData: [], // x轴数据，可根据需求
       // 在线人数数据
      onlineData:{
        data: 325,
        dayRate: '11.62%',
        weekRate: '17.62%',
        tot: 35676,
        aver: 365,
        dataArr:[320, 332, 301, 334, 390, 330, 320]
      },
      // 付费金额
      paymentData:{
        data: 325,
          dayRate: '-11.62%',
          weekRate: '-17.62%',
          tot: 35,
          aver: 5,
          dataArr:['10', '8',  '6',  '12',  '15', '8', '9']
      },
      onlineChart: { id: "online", unit: "人" },
      paymentChart: { id: "payment", unit: "万" },
      tableData: [], // 表格主数据
      tableLoading: false,
    };
  },
  created() {
      //默认显示最近一周的日期
      var now = new Date();
      var sDay = new Date(now.getTime() - 24 * 3600 * 1000 * 7);
      var syear = sDay.getFullYear();
      var smonth = sDay.getMonth();
      var start_day = sDay.getDate();
      var eDay = new Date(now.getTime()- 24 * 3600 * 1000);
      var eyear = eDay.getFullYear();
      var emonth = eDay.getMonth();
      var end_day = eDay.getDate();
      this.startDate =this.doHandleDate(smonth+1)+"-"+this.doHandleDate(start_day);
      this.endDate = this.doHandleDate(emonth+1)+"-"+this.doHandleDate(end_day);
      this.endDateStr = this.endDate+"("+this.formatDay(eDay.getDay())+")";
  //    console.log(eDay)
      //console.log(smonth)
      //console.log(start_day)
      //console.log(end_day)
  //    console.log(this.formatDay(now.getDay()));
      this.dateRange = [new Date(syear, smonth, start_day, 0, 0), new Date(eyear, emonth, end_day, 0, 0)];
      this.geGameData();
//    选择的日期范围相差几天
      var days=this.datedifference(this.formatDate(this.dateRange[0]),this.formatDate(this.dateRange[1]));
      for(var i=0;i<days+1;i++){
        this.xAxisData.push(this.getDay(i))
      }
//      console.log(this.xAxisData);
//    this.xAxisData=[this.getDay(date,-7),this.getDay(date,-6),this.getDay(date,-5),this.getDay(date,-4),this.getDay(date,-3),this.getDay(date,-2),this.getDay(date,-1)]
//    console.log(this.xAxisData);
  },
  mounted() {

  },
  methods: {
    // 判断是星期几
    formatDay(day) {
      var days='';
      switch(day) {
        case 1:
          days = '星期一';
          break;
        case 2:
          days = '星期二';
          break;
        case 3:
          days = '星期三';
          break;
        case 4:
          days = '星期四';
          break;
        case 5:
          days = '星期五';
          break;
        case 6:
          days = '星期六';
          break;
        case 0:
          days = '星期日';
          break;
      }
      return days;
    },
    // 日期格式转化为yyyy-MM-dd HH:mm:ss
    formatDate(date) {
      var date = new Date(date);
      var year = date.getFullYear();
      var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
      var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
      var H = date.getHours();
      H = H < 10 ? '0' + H : H;
      var Mi = date.getMinutes();
      Mi = Mi < 10 ? '0' + Mi : Mi;
      var S = date.getSeconds();
      S = S < 10 ? '0' + S : S;
      return year + '-' + month + '-' + day + ' ' + H + ':' + Mi + ':' + S;
    },
    getDay(day){
//      var today = new Date();
      var today = this.deepCopy(this.dateRange[0]);
//      console.log(today);
      var targetday_milliseconds=today.getTime() + 1000*60*60*24*day;
      today.setTime(targetday_milliseconds); //注意，这行是关键代码
      var tYear = today.getFullYear();
      var tMonth = today.getMonth();
      var tDate = today.getDate();
      tMonth = this.doHandleDate(tMonth + 1);
      tDate = this.doHandleDate(tDate);
//      return tYear+"-"+tMonth+"-"+tDate;
      return tMonth+"-"+tDate;
    },
    //两个时间相差天数 兼容firefox chrome
    datedifference(sDate1, sDate2) {    //sDate1和sDate2是2006-12-18格式
      var dateSpan,
        tempDate,
        iDays;
      sDate1 = Date.parse(sDate1);
      sDate2 = Date.parse(sDate2);
      dateSpan = sDate2 - sDate1;
      dateSpan = Math.abs(dateSpan);
      iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
      return iDays
    },
    doHandleDate(date){
      var d = date;
      if(date.toString().length == 1){
        d = "0" + date;
      }
      return d;
    },
    deepCopy(obj, cache = new WeakMap()) {
        if (!obj instanceof Object) {
          return obj;
        }
        // 防止循环引用
        if (cache.get(obj)) {
          return cache.get(obj)
        }
        // 支持函数
        if (obj instanceof Function) {
          return function () {
            obj.apply(this, arguments);
          }
        }
        // 支持日期
        if (obj instanceof Date) {
          return new Date(obj)
        }
        // 支持正则对象
        if (obj instanceof RegExp) {
          return new RegExp(obj.source, obj.flags)
        }
        // 还可以增加其他对象,比如:map, set 等,根据情况判断增加极客

        // 数组是 key 为数字的特殊对象
        const res = Array.isArray(obj) ? [] : {}

        // 缓存 copy 的对象,用于处理循环引用的情况
        cache.set(obj, res)

        Object.keys(obj).forEach(key => {
          if (obj[key] instanceof Object) {
          res[key] = deepCopy(obj[key], cache)
          } else {
            res[key] = obj[key]
          }
        })
        return res
    },
    //选择平台
    choosePlat() {
      console.log(this.platform);
      this.geGameData();
    },
    //选择日期范围
    chooseDate() {
      this.startDate =(this.formatDate(this.dateRange[0])).slice(5,10);
      this.endDate = (this.formatDate(this.dateRange[1])).slice(5,10);
      this.endDateStr = this.endDate+"("+this.formatDay(this.dateRange[1].getDay())+")";
      this.geGameData();
//     获取数据后动态渲染图表
      var days=this.datedifference(this.formatDate(this.dateRange[0]),this.formatDate(this.dateRange[1]));
//      console.log(days);
      this.xAxisData=[];
      for(var i=0;i<days+1;i++){
        this.xAxisData.push(this.getDay(i))
      }
//      console.log(this.xAxisData);
      this.paymentData={
        data: 500,
        dayRate: '-11.62%',
        weekRate: '-17.62%',
        tot: 35,
        aver: 15,
        dataArr:['10', '8',  '6',  '12']
      };
    },
    // 获取
    geGameData() {
      this.tableLoading = true;
      if (this.platform == "all") {
        let task = [this.getWyState(), this.getWebState()];
        Promise.all(task).then((res) => {
          this.tableData = res[0].concat(res[1]);
          this.tableData.map((item, index) => (item.index = index + 1));
          this.initTableData();
        });
      } else if (this.platform == "h5") {
          this.getWyState().then((res) => {
          this.tableData = res;
          this.initTableData();
        });
      } else {
          this.getWebState().then((res) => {
          this.tableData = res;
          this.initTableData();
        });
      }
    },
    initTableData() {
      this.tableLoading = false;
      // 提前计算，便于排序
      let day =
        (Date.parse(this.endDate) - Date.parse(this.startDate)) /
        (1 * 24 * 60 * 60 * 1000) +
        1;
      this.tableData.map((obj, i) => {
        obj.index = i + 1;
        obj.payRate = obj.pays
          ? parseFloat(((obj.pays / obj.logins) * 100).toFixed(1))
          : 0;
        obj.actives = obj.actives ? Math.floor(obj.actives / day) : 0;
        obj.arpu = obj.arpu
          ? obj.arpu
          : !!obj.logins && !!obj.pay
          ? parseFloat((obj.pay / obj.logins).toFixed(2))
          : 0;
        obj.arppu = obj.arppu
          ? obj.arppu
          : !!obj.pays && !!obj.pay
          ? parseFloat((obj.pay / obj.pays).toFixed(2))
          : 0;
        obj.odpayRate = obj.odpays
          ? parseFloat(((obj.odpays / obj.odlogins) * 100).toFixed(1))
          : 0;
        obj.npayRate = obj.npays
          ? parseFloat(((obj.npays / obj.nlogins) * 100).toFixed(1))
          : 0;
        obj.ltv = obj.pay_0 ? parseFloat((obj.pay_0 / obj.reg).toFixed(2)) : 0;
        obj.ltv7 = obj.pay_7 ? parseFloat((obj.pay_7 / obj.reg).toFixed(2)) : 0;
        obj.ltv15 = obj.pay_15
          ? parseFloat((obj.pay_15 / obj.reg).toFixed(2))
          : 0;
        obj.ltv30 = obj.pay_30
          ? parseFloat((obj.pay_30 / obj.reg).toFixed(2))
          : 0;
        obj.ltv60 = obj.pay_60
          ? parseFloat((obj.pay_60 / obj.reg).toFixed(2))
          : 0;
        obj.ltv120 = obj.pay_120
          ? parseFloat((obj.pay_120 / obj.reg).toFixed(2))
          : 0;
        obj.role_rate = obj.role_rate
          ? (obj.role_rate * 100).toFixed(0) * 1
          : !!obj.reg && !!obj.nroles
          ? ((obj.nroles / obj.reg) * 10000).toFixed(0) * 1
          : 0;
      });
    },
    getWyState() {
      return new Promise((resolve, reject) => {
          let queryObj = {
            sdate: this.formatDate(this.dateRange[0]),
            edate: this.formatDate(this.dateRange[1]),
          };
        this.$api.wyGameReport(queryObj).then((res) => {
          if (res.code == "0") {
            res.data.forEach(function (obj, i) {
              obj.index = i + 1;
            });
            resolve(res.data);
          }
         });
      });
    },
    getWebState() {
      return new Promise((resolve, reject) => {
          let queryObj = {
            date_s: this.formatDate(this.dateRange[0]),
            date_e: this.formatDate(this.dateRange[1]),
          };
        this.$api.webGameReport(queryObj).then((res) => {
          if (res.code == "101") {
            res.data.forEach(function (obj, i) {
              obj.index = i + 1;
            });
            resolve(res.data);
          }
        });
      });
    },

  }

};
</script>
<style lang="css" scoped>
.dashbord {
  margin-top: 20px;
}
.info{
  font-size:14px;
  color:#7b7b7b;
}
.data .num{
  font-size:40px;
}
.info .number{
  font-size: 16px;
  font-weight: bold;
}
.rate{
  font-weight:bold;
}
.rate.top{
  color:#2DCA93;
}
.rate.bottom{
  color:#FC6772;
}
.el-date-editor .el-range-separator {
  width: 8% !important;
}
  .flRate{float:left;}
  .flRate .info{margin:5px 5px;}
  .flNum{
    float: left;
    width: 50%;
    border-left: 1px solid rgb(235, 238, 245);
  }
  .flNum .info{margin:12px 10px;}
</style>
